#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import six
import logging
import requests
import urllib2

mailgun_key = 'key-5aaeb9520572dce446b57b697a26107e'


def utf8(string):
    """
    Make sure string is utf8 encoded bytes.

    If parameter is a object, object.__str__ will been called before encode as bytes
    """
    if isinstance(string, six.text_type):
        return string.encode('utf8')
    elif isinstance(string, six.binary_type):
        return string
    else:
        return six.text_type(string).encode('utf8')




def send_mail_requests(to, subject, text=None, html=None, async=False, _from="xiyoulaoyuanjia", attachment=None):
    logging.info('send_mail module runnig...')

    if not mailgun_key:
        logging.debug('mailgun key not config')
        return


    #url_file = urllib2.urlopen(attachment)

    r = requests.post("https://api.mailgun.net/v2/mail.freekindle.mobi/messages",\
              auth=("api", mailgun_key),
              files={
                  #"attachment[1]": (attachment.rsplit('/')[-1], url_file)
              },
              timeout=10 * 60,
              data={
                    "html": utf8(html),
                    'from': utf8(_from),
                    'to': utf8(to),
                    'subject': utf8(subject),
              })
    if r.status_code != 200:
        raise Exception(r.text)
    else:
        logging.debug(r.text) 

    logging.info('send_mail module exiting...')



if __name__ == '__main__':
	send_mail_requests('825823776@qq.com', subject="网页刷新失败,请人工干预", text=None, html=None, async=False, _from="xiyoulaoyuanjia@gmail.com", attachment=None)
	

